/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
XhrUploader = {

};

XhrUploader.prototype = {
    opts: {
        processUpdated: function (index, file, currentProgress, speed) {
        }
    },

    upload: function () {
        var me = this;
        if (!me.files) return me.opts.error(me.errors[0]), !1;
        var t = function () {
            if (!Airdroid.DeviceManage.isCurrentDeviceConnected()) return me.cancelAll(function () {
                    for (; me.files.length > 0;) {
                        var t = me.files.shift();
                        me.opts.error(me._commonLang.upload_network_error, t)
                    }
                    _.each(me.uploadXHRs,
                        function (t) {
                            t.upload.file && (t.abort(), me.clearResendTimeId(t), me.uploadXHRs = _.without(me.uploadXHRs, t), me.opts.error(me._commonLang.upload_network_error, t.upload.file))
                        })
                },
                !0),
                !1;
            for (; me.uploadXHRs.length < me.opts.maxfiles && me.files.length > 0 && !me.isCancel;) {
                var file = me.files.shift();
                try {
                    if (!me.checkAllowUpload(file)) {
                        me.uploadError(null, file);
                        continue
                    }
                    me.uploadFile(file)
                } catch (i) {
                    return me.opts.error(me.errors[3]),
                        !1
                }
            }
        };
        me.checkSendGetBeforeUpload() ? Airdroid.Util.getHttpsUpload(function () {
            t()
        }) : t()
    },


    uploadFile: function (file/*File*/) {
        var me = this,
            xhr = new XMLHttpRequest,
            startTime = (new Date).getTime();

        xhr.reSendTimeId = null;
        xhr.upload.file = file;
        xhr.upload.currentStart = startTime;
        xhr.upload.currentProgress = 0;

        // upload complete
        xhr.onload = function (e) {
            me.clearResendTimeId(xhr);

            var xhr = e.currentTarget;
            if (xhr.responseText) {
                me.uploadXHRs = _.without(me.uploadXHRs, xhr);
                var time = (new Date).getTime() - startTime;

                "." != xhr.upload.file.name && me.opts.uploadFinished(xhr.upload.file.index, xhr.upload.file, xhr.responseText, time);
                0 == me.files.length && 0 == me.uploadXHRs.length && me.afterAll();
                me.upload();
            }
        };
        // upload failed
        xhr.onerror = function () {
            me.clearResendTimeId(xhr);
            me.uploadError(xhr.upload.file.index, xhr.upload.file);
        };

        me.opts.params && (me.opts.params.fn = me.getFilePath(file), me.opts.params.fname = me.getFilePath(file), me.opts.params.needSize && (me.opts.params.fsize = file.size, delete me.opts.params.needSize));

        var uploadUrl = me.opts.url;
        Airdroid.Util.browser.ie10 || Airdroid.Util.browser.ie11 ? (me.opts.params = me.opts.params || {},
            me.opts.params.account_sid = Airdroid.Util.getCookie("account_sid") || "") : xhr.withCredentials = !0,

            uploadUrl = /\?/.test(me.opts.url) ? me.opts.url + "&" + $.param(me.opts.params) : me.opts.url + "?" + $.param(me.opts.params),

            console.info("uploadUrl ===> " + uploadUrl),
            xhr.open("POST", uploadUrl, true),
            xhr.setRequestHeader("Content-Type", "application/octet-stream"),
            "." != file.name && xhr.upload.addEventListener("progress", me.onProgress, false),
            xhr.send(file),

            me.checkSendGetBeforeUpload() && (xhr.reSendTimeId = setTimeout(function () {
                0 == xhr.upload.currentProgress && (console.debug(""), me.uploadXHRs = _.without(me.uploadXHRs, xhr), xhr.abort(), Airdroid.Util.getHttpsUpload(function () {
                    me.uploadFile(file)
                }))
            },
            15e3)),
            me.uploadXHRs.push(xhr)
    },

    clearResendTimeId: function (xhr) {
        xhr.reSendTimeId && clearTimeout(xhr.reSendTimeId);
    },

    onUploadFinished: function (index, file, responseText, time) {

    },

    onUploadError: function (index, file) {

    },

    onProgress: function (e) {
        var me = this, upload = e.target;
        if (e.lengthComputable && me.opts) {
            var n = Math.round(100 * e.loaded / e.total);
            if (upload.currentProgress != n) {
                upload.currentProgress = n;
                var speed = "0Kb/s";
                me.opts.progressUpdated(upload.file.index, upload.file, upload.currentProgress, speed);
            }
        }
    },

    formatSize : function(size) {

        if (size === undefined || /\D/.test(size)) {
            return 'N/A';
        }

        function round(num, precision) {
            return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision);
        }

        var boundary = Math.pow(1024, 4);

        // TB
        if (size > boundary) {
            return round(size / boundary, 1) + " " + 'TB';
        }

        // GB
        if (size > (boundary/=1024)) {
            return round(size / boundary, 1) + " " + 'GB';
        }

        // MB
        if (size > (boundary/=1024)) {
            return round(size / boundary, 1) + " " + 'MB';
        }

        // KB
        if (size > 1024) {
            return Math.round(size / 1024) + " " + 'KB';
        }

        return size + " " + 'B';
    }

};
